package com.capgemini.poste.metier;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.capgemini.poste.dao.Event;
import com.capgemini.poste.dao.User;
import com.capgemini.poste.dao.UserPK;

public class Login extends com.capgemini.poste.dao.User {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7231034930466525867L;
	static HashSet<User>  users = new HashSet<User>();
	
	public Login(EntityManager em) {
		// Create the query and populate the Hashset with users retrieved from DTB
		Query getAllUsers = em.createQuery("select u from User u" ) ;
		@SuppressWarnings("unchecked")
		List<User> results = getAllUsers.getResultList() ;
		for ( User result : results ) {
			users.add(result) ;
		}

	}

	public ArrayList<Event> retrieve(XSSFSheet excelSheet) {
		// TODO Auto-generated method stub
		XSSFRow row ;
		boolean bFirst = true ;
		ArrayList<Event> events = new ArrayList<Event>() ;
		
		for ( Iterator<Row> rowIterator = excelSheet.rowIterator(); rowIterator.hasNext();) {
			row = (XSSFRow)rowIterator.next() ;
			// Skip the header row
			if ( bFirst == true) {
               row = (XSSFRow) rowIterator.next();
               bFirst = false ;
            }
			
			UserPK id = new UserPK() ;
			User user = new User() ;
			id.setCd(row.getCell(1).getStringCellValue().toUpperCase()) ;
			user.setId(id);
			user.setLbNom(id.getCd()) ;
			
			if ( users.add ( user ) == true ) {
				System.out.println ( "User  " + user.getLbNom() + " has been added !!");
				Event event = new Event () ;
				event.setType(POSTE.LOGIN) ;
				event.setCd(user.getLbNom()) ;
				events.add(event) ;
			}
		}
		return events ;
	}

	public ArrayList<Event> retrieve (XSSFWorkbook excelWorkbook ) {
		// TODO Auto-generated method stub
		ArrayList<Event> events = new ArrayList<Event>() ;

		events = this.retrieve(excelWorkbook.getSheetAt(0)) ;
		events.addAll( this.retrieve(excelWorkbook.getSheetAt(1)) ) ;
		events.addAll( this.retrieve(excelWorkbook.getSheetAt(2)) ) ;
		
		return events ;
	}
	
	public int getSize ( ) {
		return users.size() ;
	}
	
	public void save ( EntityManager em ) {
		for ( Iterator<User> u = users.iterator(); u.hasNext() ;) {
			em.persist(u.next()) ;
		}
	}
	
	public User get ( String Cd ) {
		User login = new User () ;
		
		for ( Iterator<User> u = users.iterator(); u.hasNext() ;) {
			login = u.next() ;
			if ( login.getId().getCd().equals(Cd) == true ) {
				break ;
			}
		}		
		
		return login ;
	}
	
}
